package com.kinon.ogt.api.convert;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * 佛祖保佑 永无BUG
 *
 * @author WangZhiYao
 * @date 2018/4/25
 */
public final class GsonConvertFactory extends Converter.Factory {

    private final Gson mGson;

    private GsonConvertFactory(Gson gson) {
        if (gson == null) {
            throw new NullPointerException("mGson == null");
        }
        this.mGson = gson;
    }

    public static GsonConvertFactory create() {
        return create(new Gson());
    }

    public static GsonConvertFactory create(Gson gson) {
        return new GsonConvertFactory(gson);
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = mGson.getAdapter(TypeToken.get(type));
        return new GsonResponseConverter<>(mGson, adapter, type);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                          Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = mGson.getAdapter(TypeToken.get(type));
        return new GsonRequestConverter<>(mGson, adapter);
    }
}
